package com.yzl.frelink.service.pattern;

import org.springframework.stereotype.Component;

import com.yzl.frelink.entities.chart.Parameter;
import com.yzl.frelink.entities.chart.StateTree;
import com.yzl.frelink.entities.chart.StateTreeNode;
import com.yzl.frelink.entities.chart.Transition;
import com.yzl.frelink.entities.component.Chart;

@Component
public class Timer {
    // 名称
    // 启动标志
    // 关闭标志
    // 超时标志
    // 时间
    // 重置标志
    public Chart getTimerPattern(String name) {
        Chart chart = new Chart(name);
        StateTree tree = new StateTree();
        chart.addState(new StateTreeNode("start", StateTreeNode.START));
        tree.addChild(chart.getState("start"));
        // off
        chart.addState(new StateTreeNode(name + "_off", StateTreeNode.NORMAL));
        tree.addChild(chart.getState(name + "_off"));
        Transition tr1 = new Transition(chart.getState("start"), chart.getState(name + "_off"));
        chart.addTransition(tr1);
        // on
        chart.addState(new StateTreeNode(name + "_on", StateTreeNode.NORMAL));
        tree.addChild(chart.getState(name + "_on"));
        Transition tr2 = new Transition(chart.getState(name + "_off"), chart.getState(name + "_on"));
        tr2.setGuard("start_"+name);
        chart.addTransition(tr2);
        chart.addParameter(new Parameter("start_"+name, Parameter.INPUT));

        // reset
        Transition tr3 = new Transition(chart.getState(name + "_on"), chart.getState(name + "_on"));
        tr3.setGuard("reset_"+name);
        chart.addTransition(tr3);
        chart.addParameter(new Parameter("reset_"+name, Parameter.INPUT));

        // stop
        Transition tr4 = new Transition(chart.getState(name + "_on"), chart.getState(name + "_off"));
        tr4.setGuard("stop_"+name);
        chart.addTransition(tr4);
        chart.addParameter(new Parameter("stop_"+name, Parameter.INPUT));

        // timeout
        chart.addState(new StateTreeNode(name + "_timeout", StateTreeNode.NORMAL));
        chart.getState(name+"_timeout").addEntryAction(name+"_expired = true;");
        tree.addChild(chart.getState(name + "_timeout"));
        Transition tr5 = new Transition(chart.getState(name + "_on"), chart.getState(name + "_timeout"));
        tr5.setEvent("after(" + name + "_timeout_duration, msec)");
        chart.addParameter(new Parameter(name + "_timeout_duration", Parameter.INPUT));
        chart.addParameter(new Parameter(name + "_expired", Parameter.OUTPUT));
        chart.addTransition(tr5);

        Transition tr6 = new Transition(chart.getState(name + "_timeout"), chart.getState(name + "_off"));
        chart.addTransition(tr6);

        chart.setStateTree(tree);
        chart.setPortOrder();
        return chart;
    }
    // timer_off --> timer_on : start
    // timer_on --> timer_off : stop
    // timer_on --> timer_on : reset
    // timer_on : en: timer = 0
    // du: timer = timer + 1
    // if timer >= time
    //     timeout = true;
    // end
}
